import { Button, Card, Col, Form, Input, message, Radio, Row, Select, DatePicker } from "antd";
import { addon } from "pao-aop";
import { reactControl, ReactView, ReactViewControl, ReactViewState } from "pao-aop-client";
import React from "react";
import { MainCard } from "src/business/components/style-components/main-card";
import { MainContent } from "src/business/components/style-components/main-content";
import { AppServiceUtility } from "src/projects/app/appService";
import { ROUTE_PATH } from "src/projects/router";
import TextArea from "antd/lib/input/TextArea";
import { ModalSearch } from "src/business/components/buss-components/modal-search";
import { InputType as ListInputType } from "src/business/components/buss-components/sign-frame-layout";

/**
 * 组件：服务订单新增状态
 */
export interface ChangeServiceOrderViewState extends ReactViewState {
    /** 项目列表 */
    item_list?: any[];
    /** 项目列表集合 */
    all_item_list?: any[];
    /** 基础数据 */
    base_data?: {};
    /** 服务商编号 */
    service_provider_list?: any[];
}
export interface ChangeServiceOrderFormValues {
    id?: string;
}
/**
 * 组件：服务订单新增
 * 描述
 */
export class ChangeServiceOrderView extends ReactView<ChangeServiceOrderViewControl, ChangeServiceOrderViewState> {
    private columns_data_source = [{
        title: '编号',
        dataIndex: 'code',
        key: 'code',
    }, {
        title: '名称',
        dataIndex: 'name',
        key: 'name',
    }, {
        title: '身份证号',
        dataIndex: 'id_card',
        key: 'id_card',
    },];
    private columns_data_source_per = [{
        title: '编号',
        dataIndex: 'code',
        key: 'code',
    }, {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
    }, {
        title: '身份证号',
        dataIndex: 'id_card',
        key: 'id_card',
    }, {
        title: '性别',
        dataIndex: 'sex',
        key: 'sex',
    }, {
        title: '出生年月',
        dataIndex: 'birth_date',
        key: 'birth_date',
    }];
    /** 总项目列表 */
    constructor(props: any) {
        super(props);
        this.state = {
            item_list: [],
            all_item_list: [],
            base_data: {},
            service_provider_list: []
        };
    }
    /** 提交方法 */
    handleSubmit = (e: any) => {
        e.preventDefault();
        const { form } = this.props;
        form!.validateFields((err: Error, values: ChangeServiceOrderFormValues) => {
            let formValue = {};
            let service_item: any = [];
            this.state.all_item_list!.map(() => {
                service_item.push({ service_options: [] });
            });
            for (let key in values) {
                if (key.indexOf('___') !== -1) {
                    let keys = key.split('___');
                    if (keys[0] === 'service_item' || keys[0] === 'service_type') {
                        service_item[parseInt(keys[1], undefined)][keys[0]] = values[key];
                    } else {
                        service_item[parseInt(keys[1], undefined)]['service_options'].push({ 'id': keys[0], 'value': values[key], 'name': keys[2] });
                    }

                } else {
                    formValue[key] = values[key];
                }
            }
            formValue['service_item'] = service_item;
            AppServiceUtility.service_operation_service.update_service_order!(formValue)!
                .then((data) => {
                    if (data) {
                        message.info('保存成功');
                        this.props.history!.push(ROUTE_PATH.serviceOrder);
                    }
                });
        });
    }

    componentDidMount() {
        // AppServiceUtility.service_operation_service.get_service_provider_list!({})!
        //     .then((data: any) => {
        //         if (data) {
        //             let service_provider = data.result.map((key: any, value: any) => {
        //                 return <Select.Option key={key.id}>{key.name}</Select.Option>;
        //             });
        //             this.setState({
        //                 service_provider_list: service_provider
        //             });
        //         }
        //     });
        AppServiceUtility.services_project_service.get_services_project_list!({})!
            .then((data: any) => {
                if (data) {
                    this.setState({
                        item_list: data['result']
                    });
                }
            });
        AppServiceUtility.service_operation_service.get_service_provider_list_all!({})!
            .then((data: any) => {
                if (data) {
                    this.setState({
                        service_provider_list: data['result']
                    });
                }
            });
        if (this.props.match!.params.key) {
            AppServiceUtility.service_order_service.get_service_order_list!({ id: this.props.match!.params.key })!
                .then((data) => {
                    console.info(data);
                    this.setState({
                        base_data: data!.result![0],
                        all_item_list: data!.result![0]['detail'],
                    });
                });
        }
    }
    itemOnChange = (value: any, option: any) => {
        let list: any[] = this.state.all_item_list!;
        AppServiceUtility.services_project_service.get_services_project_list!({ id: value })!
            .then((data: any) => {
                if (list.length > 0 && data) {
                    list[option.key] = data.result[0];
                    this.setState({
                        all_item_list: list
                    });
                }
            });
    }
    /** 返回按钮 */
    retBtn = () => {
        this.props.history!.push(ROUTE_PATH.serviceOrder);
    }
    /** 添加项目按钮 */
    addItem = () => {
        let list: any[] = this.state.all_item_list!;
        list.push({});
        this.setState({
            all_item_list: list
        });
    }
    render() {
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 5 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
            },
        };
        const { getFieldDecorator } = this.props.form!;
        let modal_search_items_props = {
            edit_form_items_props: [
                {
                    type: ListInputType.input,
                    label: "服务商名称",
                    decorator_id: "name"
                },
            ],
            columns_data_source: this.columns_data_source,
            service_name: AppServiceUtility.personnel_service,
            service_func: 'get_organizational_list_all',
            title: '服务商查询',
            select_option: {
                placeholder: "请选择服务商",
            }
        };
        let modal_search_items_props_per = {
            edit_form_items_props: [
                {
                    type: ListInputType.input,
                    label: "采购人名称",
                    decorator_id: "name"
                },
            ],
            columns_data_source: this.columns_data_source_per,
            service_name: AppServiceUtility.personnel_service,
            service_func: 'get_personnel_list_all',
            title: '采购人查询',
            select_option: {
                placeholder: "请选择采购人",
            }
        };
        // 如果服务项目不为空则生成
        let item_list;
        if (this.state.all_item_list!.length > 0) {
            item_list = this.state.all_item_list!.map((value, index) => {
                return (
                    <Card key={index}>
                        <Row type="flex" justify="center">
                            <Col span={12}>
                                <Form.Item label='服务项目'>
                                    {getFieldDecorator('service_item___' + index, {
                                        initialValue: value.service_item ? value.service_item : '',
                                        rules: [{
                                            required: true,
                                            message: '请选择服务项目'
                                        }],
                                    })(
                                        <Select showSearch={true} key={index} onChange={this.itemOnChange}>
                                            {this.state.item_list!.map((key) => {
                                                return <Select.Option key={index} value={key['id']}>{key['name']}</Select.Option>;
                                            })}
                                        </Select>
                                    )}
                                </Form.Item>
                                {
                                    value.type_name ? (
                                        <Form.Item label='服务类型'>
                                            {getFieldDecorator('service_type___' + index, {
                                                initialValue: value.type_name,
                                                rules: [{
                                                    required: false,
                                                }],
                                                option: {
                                                    disabled: true
                                                }
                                            })(
                                                <Input />
                                            )}
                                        </Form.Item>
                                    ) : ''
                                }
                                {
                                    value.service_options ? value.service_options.map((service_options: any, indexs: any) => {
                                        return (
                                            <Form.Item label={service_options.name} key={index}>
                                                {getFieldDecorator(service_options.id + '___' + index + '___' + service_options.name, {
                                                    initialValue: '',
                                                    rules: [{
                                                        required: false,
                                                    }],
                                                })(
                                                    <Radio.Group>
                                                        {
                                                            service_options.option_content!.map((item: any, content: any) => {
                                                                return <p key={content}><Radio value={item.option_value}>{item.option_content}</Radio></p>;
                                                            })
                                                        }
                                                    </Radio.Group>
                                                )}
                                            </Form.Item>
                                        );
                                    }) : ''
                                }
                            </Col>
                        </Row>
                    </Card>
                );
            });
        }
        return (
            <MainContent>
                <Form {...formItemLayout} onSubmit={this.handleSubmit}>
                    <MainCard title='服务订单'>
                        <Col >

                            <Form.Item label='服务商'>
                                {getFieldDecorator('service_provider_id', {
                                    initialValue: this.state.base_data!['service_provider_id'] ? this.state.base_data!['service_provider_id'] : [],
                                    rules: [{
                                        required: false,
                                        message: '请选择服务商'
                                    }],
                                })(
                                    // <Select showSearch={true}  >
                                    //     {this.state.service_provider_list!.map((value,index) => {
                                    //         return <Select.Option key={index}  value={value['id']}>{value['user_name']}</Select.Option>;
                                    //     })}
                                    // </Select>
                                    <ModalSearch modal_search_items_props={modal_search_items_props} />
                                )}
                            </Form.Item>
                            <Form.Item label='采购人'>
                                {getFieldDecorator('purchaser_id', {
                                    initialValue: this.state.base_data!['purchaser_id'] ? this.state.base_data!['purchaser_id'] : '',
                                    rules: [{
                                        required: false,
                                        message: '请选择采购人'
                                    }],
                                })(
                                    //     <Select showSearch={true}  >
                                    //     {this.state.purchaser_id_list!.map((value:any,index:any) => {
                                    //         return <Select.Option key={index} value={value['id']}>{value['name']}</Select.Option>;
                                    //     })}
                                    // </Select>
                                    <ModalSearch modal_search_items_props={modal_search_items_props_per} />
                                )}
                            </Form.Item>
                            <Form.Item label='订单时间'>
                                {getFieldDecorator('order_date', {
                                    initialValue: this.state.base_data!['order_date'] ? this.state.base_data!['order_date'] : '',
                                    rules: [{
                                        required: false,
                                        message: '请输入订单时间'
                                    }],
                                })(
                                    // <Input type='date'/>
                                    <DatePicker />
                                )}
                            </Form.Item>
                            <Form.Item label='服务时间'>
                                {getFieldDecorator('service_date', {
                                    initialValue: this.state.base_data!['service_date'] ? this.state.base_data!['service_date'] : '',
                                    rules: [{
                                        required: false,
                                        message: '请输入服务时间'
                                    }],
                                })(
                                    <DatePicker />
                                )}
                            </Form.Item>
                            <Form.Item label='付款时间'>
                                {getFieldDecorator('pay_date', {
                                    initialValue: this.state.base_data!['pay_date'] ? this.state.base_data!['pay_date'] : '',
                                    rules: [{
                                        required: false,
                                        message: '请输入付款时间'
                                    }],
                                })(
                                    <DatePicker />
                                )}
                            </Form.Item>
                            <Form.Item label='备注'>
                                {getFieldDecorator('remarks', {
                                    initialValue: this.state.base_data!['remarks'] ? this.state.base_data!['remarks'] : '',
                                    rules: [{
                                        required: false,
                                        message: '请输入备注'
                                    }],
                                })(
                                    <TextArea />
                                )}
                            </Form.Item>
                        </Col>
                    </MainCard>
                    <MainCard title='服务项目清单'>
                        {item_list}
                        <Button type='primary' onClick={this.addItem}>新增服务项目</Button>
                    </MainCard>
                    <Row type="flex" justify="center">
                        <Button htmlType='submit' type='primary'>保存</Button>
                        <Button type='ghost' name='返回' htmlType='button' onClick={this.retBtn}>返回</Button>
                    </Row>
                </Form>
            </MainContent>
        );
    }
}

/**
 * 控件：服务订单新增页面
 * 描述
 */
@addon('ChangeServiceOrderView', '服务订单新增页面', '描述')
@reactControl(Form.create<any>()(ChangeServiceOrderView), true)
export class ChangeServiceOrderViewControl extends ReactViewControl {
    constructor() {
        super();
    }
}